/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package model.dao.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import model.dao.GenericDAO;

/**
 *
 * @author root
 */
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public class GenericDAOImpl<T> implements Serializable, GenericDAO<T> {

  @PersistenceContext(unitName = "locacoesPU")
  private EntityManager em;
  
  private final Class<T> persistenceClass;

  public GenericDAOImpl(Class<T> persistenceClass) {
    this.persistenceClass = (Class<T>) ((ParameterizedType) 
      getClass().getGenericSuperclass()).getActualTypeArguments()[0];
  }

  @Override
  @TransactionAttribute(TransactionAttributeType.REQUIRED)
  public void insert(T obj) {
    try {
      em.persist(obj);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  @Override
  @TransactionAttribute(TransactionAttributeType.REQUIRED)
  public T update(T obj) {
    try {
      obj = em.merge(obj);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return obj;
  }

  @Override
  @TransactionAttribute(TransactionAttributeType.REQUIRED)
  public boolean remove(T obj) {
    try {
      obj = em.merge(obj);
      em.remove(obj);
      return true;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }

  @Override
  public T find(Object id) {
    return em.find(persistenceClass, id);
  }

  @Override
  public List<T> selectAll() {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<T> cq = cb.createQuery(persistenceClass);
    Root<T> obj = cq.from(persistenceClass);
    return em.createQuery(cq).getResultList();
  }
}
